<?php

namespace common\models\datas;

use common\components\extenders\MenuManage;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%attribute}}".
 *
 * @property integer $id
 * @property integer $type_id
 * @property string $name
 * @property string $attr_input_type
 * @property integer $attr_index
 * @property integer $sort
 * @property integer $is_show
 */
class Attribute extends \common\components\bases\BaseModel
{

    public $attr_values;


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%attribute}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type_id', 'attr_index', 'sort', 'is_show'], 'integer'],
            [['name'], 'string', 'max' => 100],
            [['name'], 'required'],
            [['attr_input_type'], 'string', 'max' => 20]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '自动编号'),
            'type_id' => Yii::t('common', '类型id'),
            'name' => Yii::t('common', '属性名称'),
            'attr_input_type' => Yii::t('common', '属性的添加类别'),
            'attr_index' => Yii::t('common', '属性是否可以检索'),
            'sort' => Yii::t('common', '排序'),
            'is_show' => Yii::t('common', '是否显示'),
            'attr_values' => Yii::t('common', '可选值列表'),
        ];
    }

    public function extraFields(){
        return [
            'type_name' => function(){
                return isset($this->type)?$this->type->name:'';
            },
            'input_type' => function(){
                return $this->attr_input_type =='select'? '从列表中选择': '手工录入';
            },
            'value' => function(){
                $str = '';
                if($this->attributeValue){
                    $arr = ArrayHelper::getColumn($this->attributeValue,'value');
                    $str = implode(',',$arr);
                }
                return $str;
            },
            'operate' => function(){
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
           }

        ];
    }

    public function getType(){
        return $this->hasOne(Type::className(),['id'=>'type_id']);
    }

    public function getAttributeValue(){
        return $this->hasMany(AttributeValue::className(),['attr_id'=>'id']);
    }
}
